package com.wish.contract.controller;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wish.contract.entity.Contract;
import com.wish.contract.feign.ConsumerFeign;
import com.wish.contract.feign.EmailFeign;
import com.wish.contract.feign.HouseFeign;
import com.wish.contract.service.IContractService;
import com.wish.contract.utils.WordUtil;
import com.wish.dto.contract.ConsumerDto;
import com.wish.dto.contract.ContractVo;
import com.wish.dto.contract.HouseDto;
import com.wish.dto.contract.SaveContractDto;
import com.wish.dto.login.JsonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lyk
 * @since 2022-08-19
 */
@RestController
@RequestMapping("/contract")
public class ContractController {
    @Autowired
    private IContractService contractService;

    @Autowired
    private HouseFeign houseFeign;

    @Autowired
    private ConsumerFeign consumerFeign;


    @Autowired
    private EmailFeign emailFeign;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    HttpServletRequest httpServletRequest;

    /*@Autowired
    private ProcessRuntime processRuntime;*/

    @RequestMapping("/createWord")
    public JsonResult createWord(Integer id, HttpServletResponse response){
        Contract contract = contractService.getById(id);
        List<ConsumerDto> list = consumerFeign.list(2);
        ContractVo contractVo = new ContractVo();
        BeanUtils.copyProperties(contract,contractVo);
        for (ConsumerDto consumerDto : list) {
            if(consumerDto.getId()==contract.getHouseId()){
                contractVo.setRenterName(consumerDto.getName());
                break;
            }
        }
        /** 用于组装word页面需要的数据 */
        Map<String, Object> dataMap = new HashMap<String, Object>();

        /** 组装数据 */
        dataMap.put("renterName",contractVo.getRenterName());
        dataMap.put("contractNo", contractVo.getContractNo());


        /** 文件名称，唯一字符串 */
        Random r = new Random();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        StringBuffer sb = new StringBuffer();
        sb.append(sdf1.format(new Date()));
        sb.append("_");
        sb.append(r.nextInt(100));

        //文件路径
        String filePath = "e:/pic/picimg";

        //文件唯一名称
        String fileOnlyName = "合同_"+sb+".doc";

        //文件名称
       String fileName = "合同.doc";

        /** 生成word */
        WordUtil.createWord(dataMap, WordUtil.templateName,filePath,fileOnlyName);
        HashMap<String, Object> map = new HashMap<>();
        try {
            //解决中文乱码
            filePath = URLDecoder.decode(filePath, "UTF-8");
            fileOnlyName = URLDecoder.decode(fileOnlyName, "UTF-8");
            fileName = URLDecoder.decode(fileName, "UTF-8");

            //如果文件不存在，则会跳入异常，然后可以进行异常处理
             new FileInputStream(filePath + File.separator + fileOnlyName);
            map.put("filePath",filePath);
            map.put("fileOnlyName",fileOnlyName);
            return JsonResult.successd(map);
        } catch (Exception e) {
             e.printStackTrace();
            return JsonResult.faild("有错");
        }

    }


    @RequestMapping("/download")
    public void download(String filePath, String fileOnlyName){
        try {
            //解决中文乱码
            filePath = URLDecoder.decode(filePath, "UTF-8");
            fileOnlyName = URLDecoder.decode(fileOnlyName, "UTF-8");
            //fileName = URLDecoder.decode(fileName, "UTF-8");

            //如果文件不存在，则会跳入异常，然后可以进行异常处理
             new FileInputStream(filePath + File.separator + fileOnlyName);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 合同列表接口
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/list")
    public JsonResult list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "1") int size) {
        //分页查询数据
        Page<Contract> page1 = new Page<>(page, size);
        Page<Contract> page2 = contractService.page(page1);

        //远程调用 查询所有房屋信息
        List<HouseDto> houseDtoList = houseFeign.list();
        //远程调用客户服务 查询所有房东信息
        List<ConsumerDto> landlordList = consumerFeign.list(1);
        //远程调用客户服务 查询所有租客信息
        List<ConsumerDto> renterList = consumerFeign.list(2);
        ArrayList<ContractVo> contractVos = new ArrayList<>();
        for (Contract record : page2.getRecords()) {
            //转换vo
            ContractVo contractVo = new ContractVo();
            BeanUtils.copyProperties(record,contractVo);
            //设置房源的名称
            HouseDto houseDto1 = houseDtoList.stream().filter(houseDto -> houseDto.getId().equals(record.getHouseId())).collect(Collectors.toList()).get(0);
            contractVo.setHouseName(houseDto1.getAddress());
            //设置房东的名称
            ConsumerDto consumerDto1 = landlordList.stream().filter(consumerDto -> consumerDto.getId().equals(record.getLandlordId())).collect(Collectors.toList()).get(0);
            contractVo.setLandlordName(consumerDto1.getName());
            //设置租客的名称
            ConsumerDto consumerDto2 = renterList.stream().filter(consumerDto -> consumerDto.getId().equals(record.getRenterId())).collect(Collectors.toList()).get(0);
            contractVo.setRenterName(consumerDto2.getName());
            contractVos.add(contractVo);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("list",contractVos);
        map.put("page",page2.getCurrent());
        map.put("size",page2.getSize());
        map.put("total",page2.getTotal());
        return JsonResult.successd(map);
    }

    /**
     * 新增修改合同初始化接口
     * @param id
     * @return
     */
    @GetMapping("/init")
    public JsonResult init(Integer id){
        //远程调用 查询所有房屋信息
        List<HouseDto> houseDtoList = houseFeign.list();
        //远程调用客户服务 查询所有房东信息
        List<ConsumerDto> landlordList = consumerFeign.list(1);
        //远程调用客户服务 查询所有租客信息
        List<ConsumerDto> renterList = consumerFeign.list(2);

        Snowflake snowflake=new Snowflake();
        String no = snowflake.nextIdStr();
        //封装vo给前端返回
        ContractVo contractVo = new ContractVo();
        contractVo.setContractNo(no);

        contractVo.setHouseDtoList(houseDtoList);
        contractVo.setLandlordList(landlordList);
        contractVo.setRenterList(renterList);
        //如果id不等于空 查询合同信息
        if(!StringUtils.isEmpty(id)){
            Contract contract = contractService.getById(id);
            BeanUtils.copyProperties(contract,contractVo);
        }
        return JsonResult.successd(contractVo);
    }

    /**
     * 新增或修改合同接口
     * @param saveContractDto
     * @return
     */
    @RequestMapping("/save")
    public JsonResult save(@RequestBody SaveContractDto saveContractDto) {
        //非空校验
        if (StringUtils.isEmpty(saveContractDto.getHouseId())) {
            return JsonResult.faild("不能为空");
        }
        //获取head 携带的token
        String token = httpServletRequest.getHeader("token");
        String username = (String) JWT.of(token).getPayload("username");
        System.err.println(username);

        //定义dto 接收表单参数
        Contract contract = new Contract();
        //初始化默认字段
        BeanUtils.copyProperties(saveContractDto,contract);

        contract.setContractState(1);
        contract.setCreatedTime(new Date());
        contract.setUpdatedTime(new Date());
        //合同入库
        contractService.saveOrUpdate(contract);
        //发送邮件内容
        String context = "合同编号：%s,租房人：%s,出租人： %s,合同期限： %s";
        String mailData = String.format(context, contract.getContractNo(), contract.getRenterId(), contract.getLandlordId(), contract.getStartDate());
        // 通过线程池调用远程邮件服务，实现消息发送 异步，并行
//        threadPoolTaskExecutor.execute(() -> {
//            emailFeign.send("合同编号"+contract.getContractNo(),"894910150@qq.com","1134895347@qq.com",mailData);
//        });
        // 直接调用远程邮件服务 阻塞同步
         emailFeign.send("合同编号"+contract.getContractNo(),"894910150@qq.com","1134895347@qq.com",mailData);
        //kafka 远程调用
        String uuid = UUID.randomUUID().toString();
        kafkaTemplate.send("contract",uuid, JSONUtil.toJsonStr(saveContractDto));


        //
  /*      ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("leave")
                .withProcessInstanceName(contract.getContractNo())
                .withBusinessKey(contract.getId().toString())
                .withVariable("deptLeader","admin")
                .build());*/


        return JsonResult.successd();
    }

    @RequestMapping("/del")
    public JsonResult del(Integer id){
        contractService.removeById(id);
        return JsonResult.successd();
    }


    @RequestMapping("/getHouse")
    public List<HouseDto> getHouse() {
        return houseFeign.list();
    }

    @RequestMapping("/getHouseByAddress")
    public List<HouseDto> getHouseByAddress(String address){
        return houseFeign.getHousesByName(address);
    }

    @RequestMapping("/getConsumers")
    public List<ConsumerDto> getConsumers(Integer type) {
        return consumerFeign.list(type);
    }
    @RequestMapping("/getConsumersByName")
    public List<ConsumerDto> getConsumersByName(Integer type,String name) {

        return consumerFeign.ByNameGetConsumer(name,type);
    }


}
